<template>
  <el-space
    size="large"
    direction="vertical"
    style="width: 100%"
    alignment="flex-start"
    fill
  >
    <!-- 操作按钮 -->
    <el-space size="large" direction="horizontal" alignment="flex-start">
      <el-button
        v-if="detailData.editable"
        type="primary"
        @click="handleUpdate"
      >
        修改
      </el-button>
      <el-button
        v-if="detailData.canUploadCertificationMaterials"
        type="primary"
        @click="dialogFormVisible = true"
      >
        上传立项认证材料
      </el-button>
      <el-button
        v-if="detailData.canInitiateCertificationMeeting"
        type="primary"
        @click="
          handleOpen(
            '/meetings/kickoff?association-type=PROJECT_CERTIFICATION&association-id=' +
              detailData.id
          )
        "
      >
        发起立项认证会
      </el-button>
      <el-button
        v-if="detailData.canReportOpeningDesign"
        type="primary"
        @click="handleOpen('/project/approval/report-submit')"
      >
        开题设计报告上报
      </el-button>
      <el-button>导出数据</el-button>
    </el-space>
    <!-- 操作按钮 -->
    <!-- 项目简介 -->
    <div class="project-title">
      <div class="item">
        <span class="label">立项建议ID：</span>
        <span>{{ detailData.id }}</span>
      </div>
      <div class="item">
        <span class="label">审核状态：</span>
        <span>
          {{
            dictStore.getDictLabelForValue('audit_status', detailData.status)
          }}
        </span>
      </div>
      <div class="item">
        <span class="label">记录创建人：</span>
        <span>{{ detailData.createName }}</span>
      </div>
      <div class="item">
        <span class="label">记录创建时间：</span>
        <span>
          {{
            $XEUtils.toDateString(detailData.createTime, 'yyyy-MM-dd HH:mm:ss')
          }}
        </span>
      </div>
    </div>
    <!-- 项目简介 -->
    <!-- 课题信息 -->
    <div class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon2.png" alt="" class="icon" />
          <span>课题信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="id" title="课题编号" />
          <vxe-column field="name" title="课程名称" />
          <vxe-column field="leader" title="课题负责人" />
          <vxe-column field="type" title="课题类型">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('topic_type', row.type) }}
            </template>
          </vxe-column>
          <vxe-column field="subjectAreaText" title="专业领域" />
          <vxe-column
            field="researchStartDate"
            title="研究开始时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column
            field="researchEndDate"
            title="研究结束时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column field="estimatedBudget" title="预计投入经费（万元）" />
          <vxe-column field="externalCooperationRequired" title="是否需要外协">
            <template #default="{ row }">
              {{
                dictStore.getDictLabelForValue(
                  'yes_no',
                  row.externalCooperationRequired
                )
              }}
            </template>
          </vxe-column>
          <vxe-column field="leadingUnitName" title="承担单位" />
          <vxe-column field="collaboratingUnitNames" title="协作单位" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 课题信息 -->
    <!-- 其他信息 -->
    <div class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon4.png" alt="" class="icon" />
          <span>其他信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="reportingUnitNames" title="上报单位" />
          <vxe-column field="reporterNames" title="上报人" />
          <vxe-column field="remarks" title="备注" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 其他信息 -->
    <el-card
      shadow="never"
      header="必要性：（含技术现状及对标分析）"
      :body-style="{ color: '#606266', lineHeight: 1.5 }"
    >
      <div>{{ detailData.necessity }}</div>
    </el-card>
    <el-card
      shadow="never"
      header="主要研究内容:"
      :body-style="{ color: '#606266', lineHeight: 1.5 }"
    >
      <div>
        {{ detailData.mainResearchContent }}
      </div>
    </el-card>
    <el-card
      shadow="never"
      header="主要技术经济指标:"
      :body-style="{ color: '#606266', lineHeight: 1.5 }"
    >
      <div>{{ detailData.mainTechnoeconomicIndicators }}</div>
    </el-card>
    <el-card
      v-if="detailData.preliminaryResearchResults"
      shadow="never"
      header="前期研究阶段成果（可选项）"
      :body-style="{ color: '#606266', lineHeight: 1.5 }"
    >
      <div>{{ detailData.preliminaryResearchResults }}</div>
    </el-card>
    <el-card
      shadow="never"
      header="预期成果及达到水平"
      :body-style="{ color: '#606266', lineHeight: 1.5 }"
    >
      <div>{{ detailData.anticipatedOutcomes }}</div>
    </el-card>
  </el-space>

  <el-dialog
    v-model="dialogFormVisible"
    title="上传认证材料"
    width="500"
    destroy-on-close
    align-center
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="认证材料" prop="relatedDocumentList">
        <el-upload
          v-model:file-list="ruleForm['relatedDocumentList']"
          :http-request="
            (options) => customUpload(options, 'relatedDocumentList')
          "
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          style="min-width: 100%"
        >
          <el-button type="primary" plain>
            <el-icon class="el-icon--left"><Upload /></el-icon>
            上传
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="submitForm(ruleFormRef)"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { useDictStore } from '@/store/modules/dict'
  import { postActionUpload } from '@/api/requestEvents'
  import { uploadTopic } from '@/api/project/approval/suggest'

  const props = defineProps({
    detailData: {
      type: Object,
      default: () => {},
    },
  })

  const emits = defineEmits(['getDetail'])

  const $baseMessage = inject('$baseMessage')

  const dictStore = useDictStore()
  const router = useRouter()

  const dialogFormVisible = ref(false)
  const loading = ref(false)
  const ruleFormRef = ref()
  const ruleForm = reactive({})
  const rules = reactive({
    relatedDocumentList: [
      {
        required: true,
        message: '请上传认证材料',
        trigger: 'change',
      },
    ],
  })

  // 文件上传前的检查
  const beforeUpload = (file) => {
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('上传文件大小不能超过 5MB!')
    }
    return isLt5M
  }

  const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
  }

  // 文件自定义上传
  const customUpload = async (options, key) => {
    const formData = new FormData()
    formData.append('file', options.file)
    try {
      // 调用 getFileUploadReturn 接口获取上传文件的返回信息
      const resUpload = await postActionUpload(
        '/infra/file/upload-return-obj',
        formData,
        options
      )
      if (resUpload.code === 0 && resUpload.data) {
        const fileItem = ruleForm[key].find(
          (item) => item.uid === options.file.uid
        )
        if (fileItem) {
          fileItem.name = resUpload.data.name
          fileItem.url = resUpload.data.url
          fileItem.id = resUpload.data.id
          fileItem.type = resUpload.data.type
        }

        ElMessage.success('文件上传成功')
      } else {
        ruleForm[key] = ruleForm[key].filter(
          (item) => item.uid !== options.file.uid
        )
      }
    } catch (error) {
      ElMessage.error('文件上传失败')
      console.error('文件上传失败', error)
      ruleForm[key] = ruleForm[key].filter(
        (item) => item.uid !== options.file.uid
      )
    }
  }

  //表单提交
  const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        let relatedDocumentList = []
        for (const key in ruleForm) {
          const arr = ruleForm[key].map((item) => {
            return {
              fileBusinessType: key,
              fileName: item.name,
              fileType: item.type,
              fileId: item.id,
              fileUrl: item.url,
            }
          })
          relatedDocumentList = relatedDocumentList.concat(arr)
        }
        const params = {
          id: props.detailData.id,
          relatedDocumentList,
        }
        loading.value = true

        uploadTopic(params)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              $baseMessage('上传成功')
              emits('getDetail')
            }
          })
          .finally(() => {
            dialogFormVisible.value = false
            loading.value = false
          })
      }
    })
  }

  const handleUpdate = () => {
    router.push(
      `/project/approval/suggest-submit?id=${props.detailData.id}&getType=2`
    )
  }

  const handleOpen = (url) => {
    router.push(url)
  }
</script>

<style lang="scss" scoped>
  .project-title {
    display: flex;
    align-items: center;
    width: 100%;
    min-height: 28px;
    padding: 10px;
    background: var(--vxe-table-header-background-color);

    .item {
      display: inline-flex;
      margin-right: 90px;
      font-size: $base-font-size-default;

      .label {
        color: $base-color-text-secondary;
      }
    }
  }

  .box {
    .common-title {
      display: flex;
      align-items: center;
      font-size: $base-font-size-default;
      font-weight: bold;
      color: $base-color-text-primary;

      .icon {
        margin-right: 10px;
      }
    }

    .sub-title {
      font-size: $base-font-size-small;
      font-weight: bold;
    }
  }
</style>
